<template>
  <div class="markdown-wrapper">
    <textarea ref="editor"/>
  </div>
</template>

<script lang="ts">
import Simplemde from "simplemde";
import "simplemde/dist/simplemde.min.css";
import { Component, Vue, Prop } from "vue-property-decorator";

@Component({})
export default class SimplemdeMarkdownEditor extends Vue {
  @Prop({ default: "" }) value!: string;
  @Prop({ default: () => {
    return {}
  } }) options!: Object;
  @Prop({ default: true }) localCache!: boolean;

  editor!: Simplemde

  mounted() {
    this.editor = new Simplemde(
      Object.assign(this.options, {
        element: this.$refs.editor
      })
    );
    this.addEvents();
    let content = localStorage.markdownContent;
    if (content) this.editor.value(content);
  }

  addEvents() {
    this.editor.codemirror.on("change", () => {
      let value = this.editor.value();
      if (this.localCache) localStorage.markdownContent = value;
      this.$emit("input", value);
      this.$emit("on-change", value);
    });
    this.editor.codemirror.on("focus", () => {
      this.$emit("on-focus", this.editor.value());
    });
    this.editor.codemirror.on("blur", () => {
      this.$emit("on-blur", this.editor.value());
    });
  }
}

</script>

<style lang="scss" scoped>
.markdown-wrapper {
  .editor-toolbar.fullscreen {
    z-index: 9999;
  }
  .CodeMirror-fullscreen {
    z-index: 9999;
  }
  .CodeMirror-fullscreen ~ .editor-preview-side {
    z-index: 9999;
  }
}
</style>
